from flask import Blueprint, jsonify, request
import json
from datetime import datetime
from data.db.db_manager import DBManager

chart_bp = Blueprint('chart', __name__, url_prefix='/api')
db_manager = DBManager()

def validate_user_params():
    """验证用户参数"""
    client_id = request.args.get('client')
    user_id = request.args.get('user')
    
    if not client_id or not user_id:
        return None, None, {
            "status": "error",
            "message": "client and user parameters are required"
        }
    return client_id, user_id, None

@chart_bp.route('/1.1/charts', methods=['GET'])
def get_charts():
    """获取图表列表或指定图表"""
    try:
        client_id, user_id, error = validate_user_params()
        if error:
            return jsonify(error), 400

        chart_id = request.args.get('chart')

        if not chart_id:
            # 返回图表列表
            charts = db_manager.get_user_charts(user_id, client_id)
            chart_list = []
            for chart in charts:
                chart_list.append({
                    "id": chart['chart_id'],
                    "name": chart['name'],
                    "symbol": chart['symbol'],
                    "timestamp": int(datetime.strptime(chart['updated_at'], 
                        '%Y-%m-%d %H:%M:%S').timestamp())
                })
            return jsonify({
                "status": "ok",
                "data": chart_list
            })
        
        # 加载指定图表
        chart = db_manager.get_chart(chart_id, user_id, client_id)
        if not chart:
            return jsonify({"status": "error", "message": "Chart not found"}), 404
        
        return jsonify({
            "status": "ok",
            "data": {
                "content": chart['content'],
                "id": chart['chart_id'],
                "name": chart['name'],
                "timestamp": int(datetime.strptime(chart['updated_at'], 
                    '%Y-%m-%d %H:%M:%S').timestamp())
            }
        })

    except Exception as e:
        print(f"Load chart error: {str(e)}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@chart_bp.route('/1.1/charts', methods=['POST'])
def save_chart():
    """保存图表"""
    try:
        client_id, user_id, error = validate_user_params()
        if error:
            return jsonify(error), 400

        # 处理 multipart/form-data 请求
        if 'content' in request.form:
            content = request.form['content']
        else:
            content = json.dumps(request.get_json(silent=True))
            
        if not content:
            return jsonify({
                "status": "error",
                "message": "Empty content"
            }), 400

        # 解析内容获取必要信息
        content_data = json.loads(content)
        chart_name = content_data.get('name', datetime.now().strftime('%Y%m%d_%H%M%S'))
        symbol = content_data.get('symbol', '')
        
        # 生成或获取图表ID
        chart_id = request.args.get('chart', str(abs(hash(f"{user_id}_{client_id}_{chart_name}"))))
        
        # 保存到数据库
        db_manager.save_chart(
            chart_id=chart_id,
            user_id=user_id,
            client_id=client_id,
            name=chart_name,
            symbol=symbol,
            content=content
        )
        
        return jsonify({
            "status": "ok",
            "id": chart_id,
            "timestamp": int(datetime.now().timestamp())
        })

    except Exception as e:
        print(f"Save chart error: {str(e)}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@chart_bp.route('/1.1/charts', methods=['DELETE'])
def delete_chart():
    """删除图表"""
    try:
        client_id, user_id, error = validate_user_params()
        if error:
            return jsonify(error), 400

        chart_id = request.args.get('chart')
        if not chart_id:
            return jsonify({
                "status": "error",
                "message": "Chart ID is required"
            }), 400
        
        # 从数据库删除图表
        db_manager.delete_chart(chart_id, user_id, client_id)
        
        return jsonify({"status": "ok"})

    except Exception as e:
        print(f"Delete chart error: {str(e)}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500
